// var DB = require("../lib/db_pg").DB;
var DB = require("../lib/db_mysql").DB;
var config = require('../lib/config');
var resErr = require('../lib/util.js').resErr;
var md5 = require('../lib/util.js').md5;
var async = require('async');
var http_request = require('../lib/util.js').http_request;

exports.student_list = function(req,res){

    var sql_text = "SELECT u.* FROM t_user u WHERE user_type=2";
    var tmp_params = [];
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    });
};


exports.student_add = function(req,res){
  var name = req.param('name');
  if(!name) return res.json({success:false,msg:'姓名不能为空！'});
  var mobile = req.param('mobile');
  if(!mobile) return res.json({success:false,msg:'手机号码不能为空！'})
  var sclass = req.param('class');
  if(!sclass) return res.json({success:false,msg:'班级不能为空！'});
  var db = new DB();
  async.waterfall([
    function(cb){
      var tmp_params = [];
      sql_text = "select count(1) counter from t_user where mobile = ?";
      // console.log(sql_text);
      tmp_params.push(mobile);
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) return cb(err);
        if(datas.length > 0 && datas[0].counter > 0){
          return cb('手机号码重复！');
        }
        return cb(null);
      })
    }
  ],function(err){
    if(err) return resErr(res,err);
    var sql_text = "insert into t_user set name=?,mobile=?,class=?,user_type=2";
    var tmp_params = [];

    tmp_params.push(name);
    tmp_params.push(mobile);
    tmp_params.push(sclass);
    db.query(sql_text,tmp_params,function(err,datas){
      console.log(datas);
      if (err){
        return resErr(res,err);
      }      
      return res.json({success:true,msg:'用户添加成功！'});
    })
  })
}

exports.student_upd = function(req,res){
  var id = req.param('id');
  if(!id) return res.json({success:false,msg:'用户ID不能为空！'});
  var name = req.param('name');
  if(!name) return res.json({success:false,msg:'姓名不能为空！'});
  var mobile = req.param('mobile');
  if(!mobile) return res.json({success:false,msg:'手机号码不能为空！'});
  var sclass = req.param('class');
  if(!sclass) return res.json({success:false,msg:'班级不能为空！'});

  var db = new DB();
  async.waterfall([
    function(cb){
      var tmp_params = [];
      sql_text = "select count(1) counter from t_user where mobile = ?";
      console.log(sql_text);
      tmp_params.push(mobile);
      db.query(sql_text,tmp_params,function(err,datas){
        if(err) return cb(err);
        if(datas.length > 0 && datas[0].counter > 0){
          return cb('手机号码重复！');
        }
        return cb(null);
      })
    }
  ],function(err){
    if(err) return resErr(res,err);
    var tmp_params = [];
    var sql_text = "update t_user set mobile=? ";
    tmp_params.push(mobile);
    if(name){
      sql_text += ",name=? ";
      tmp_params.push(name);
    } 
    if(sclass){
        sql_text += ",class=? ";
        tmp_params.push(sclass);
    }
    sql_text += ",user_type=2";
    sql_text += " where id=?";
    tmp_params.push(id);
    db.query(sql_text,tmp_params,function(err,datas){
      //console.log(datas);
      if (err){
        return res.json({success:false,msg:JSON.stringify(err)});
      }      
      return res.json({success:true,msg:'修改成功！'});
    })
  })
}

exports.student_del = function(req,res){
    var id = req.param('id');
    if(!id) return res.json({success: false, msg: '用户ID不能为空'});
    
    var db = new DB();
    var sql_text = 'delete from t_user where id = ?;';
    
    var tmp_params = [];
    tmp_params.push(id);
    
    db.query(sql_text, tmp_params, function(err, datas){
        console.log(datas);
        if(err){
            return resErr(res, err);
        }
        return res.json({success: true, msg: '删除成功'});
    });
}

exports.student_search_name = function(req,res){
    var sql_text;
    var db = new DB();
    var name = req.param('name');

    if(!name)
      sql_text = sql_text = "SELECT u.* FROM t_user u WHERE user_type=2";
    else
      sql_text = "SELECT u.* FROM t_user u WHERE name LIKE ? and user_type=2";

    var tmp_params = [];
    tmp_params.push(name);
    
    console.log(sql_text);
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    }); 
}

exports.get_admin_group = function(req, res){
    var sql_text;
    var user = req.session.adminuser;

    //Todo: 返回当前管理员能够操作的学生列表
    //返回格式: {{stu_id, stu_name, openid}...}
}

exports.student_get_classes = function(req,res){
    var sql_text = "select distinct class from t_user where user_type=2";
    var tmp_params = [];
    
    
    var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
    var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
    if(req.param("sort")){
        sql_text += " order by u." + req.param("sort");
        if(req.param("dir")){
            sql_text += " " + req.param("dir");
        }
    }
    
    var db = new DB();
    db.queryPage(sql_text,tmp_params,page,limit,function(err,result){
        if(err) return resErr(res, err);

        console.log(result);
        return res.json(result);
    });
}

exports.student_filter = function(req,res){
  var user_id = req.param('user_id');
  var user_name = req.param('user_name');
  var user_class = req.param('user_class');
  var params = [];


  var sql_text = "SELECT u.* FROM t_user u WHERE user_type=2";

  if (user_name) {
    sql_text += " and name=?";
    params.push(user_name);
  }
  if (user_class) {
    sql_text += " and class=?";
    params.push(user_class);
  }
  
  console.log(sql_text);
  
  var limit = parseInt(req.param("limit") || req.param("pageSize") ||'20');
  var page  = parseInt(req.param("page") || req.param("pageNum") || '1');  
  if(req.param("sort")){
      sql_text += " order by u." + req.param("sort");
      if(req.param("dir")){
          sql_text += " " + req.param("dir");
      }
  }
  
  var db = new DB();
  db.queryPage(sql_text,params,page,limit,function(err,result){
      if(err) return resErr(res, err);

      console.log(result);
      return res.json(result);
  }); 
}